package com.autumn.platform.auth.core.access.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.autumn.platform.auth.core.access.IAccessControllerHandler;
import com.autumn.platform.auth.core.access.IAccessControllerListener;
import com.autumn.platform.auth.core.access.IPermission;
import com.autumn.platform.core.context.response.IResponse;

public class BaseAccessController extends AbstractAccessController {

    /**
     * 访问控制处理器
     */
    @Autowired(required = false)
    private List<IAccessControllerHandler> handlers;

    /**
     * 访问控制侦听器
     */
    @Autowired(required = false)
    private List<IAccessControllerListener> listeners;

    @Override
    protected IResponse doPermitted(IPermission permission) throws Exception {
        AccessControllerContext context = new AccessControllerContext();
        context.setPermission(permission);
        context.setLocked(true);
        List<IAccessControllerListener> listeners = getListeners();
        try {
            if (null != listeners) {
                for (IAccessControllerListener listener : listeners) {
                    listener.before(permission);
                }
            }
            context.setLocked(false);
            this.handler(permission, context);
            context.setLocked(true);
            if (null != listeners) {
                boolean pass = context.isSuccess();
                for (IAccessControllerListener listener : listeners) {
                    if (pass) {
                        listener.onPass(permission, context);
                    } else {
                        listener.onDeny(permission, context);
                    }
                }
            }
        } catch (Exception e) {
            if (null != listeners) {
                for (IAccessControllerListener listener : listeners) {
                    listener.onException(permission, context, e);
                }
            }
            throw e;
        }
        return context;
    }

    private void handler(IPermission permission, AccessControllerContext context) throws Exception {
        List<IAccessControllerHandler> handlers = getHandlers();
        if (null != handlers) {
            for (IAccessControllerHandler handler : handlers) {
                handler.handler(permission, context);
                if (!context.isSuccess()) {
                    break;
                }
            }
        }
    }

    public List<IAccessControllerHandler> getHandlers() {
        return handlers;
    }

    public void setHandlers(List<IAccessControllerHandler> handlers) {
        this.handlers = handlers;
    }

    public List<IAccessControllerListener> getListeners() {
        return listeners;
    }

    public void setListeners(List<IAccessControllerListener> listeners) {
        this.listeners = listeners;
    }
}
